package top.lishuoboy.dependency.base.time;


import cn.hutool.core.util.StrUtil;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

/**
 * 时间工具类
 * 2023-12-23
 *
 * @author lishuoboy
 */
public class MyDurationUtil {

    /**
     * 字符串转Duration
     * 天：d
     * 时、分、秒：h、m、s
     * 毫秒、微妙、纳秒：ms、us、ns
     *
     * @param durationStr       间隔字符串
     * @param chronoUnitDefault 默认时间单位。当durationStr为纯数字时，使用此单位
     */
    public static Duration parseDuration(String durationStr, ChronoUnit chronoUnitDefault) {
        if (StrUtil.endWithIgnoreCase(durationStr, "ns")) {
            return Duration.ofNanos(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "ns", "")));
        } else if (StrUtil.endWithIgnoreCase(durationStr, "us")) {
            return Duration.ofNanos(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "us", "")) * 1000);
        } else if (StrUtil.endWithIgnoreCase(durationStr, "ms")) {
            return Duration.ofMillis(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "ms", "")));
        } else if (StrUtil.endWithIgnoreCase(durationStr, "s")) {
            return Duration.ofSeconds(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "s", "")));
        } else if (StrUtil.endWithIgnoreCase(durationStr, "m")) {
            return Duration.ofMinutes(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "m", "")));
        } else if (StrUtil.endWithIgnoreCase(durationStr, "h")) {
            return Duration.ofHours(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "h", "")));
        } else if (StrUtil.endWithIgnoreCase(durationStr, "d")) {
            return Duration.ofDays(Long.parseLong(StrUtil.replaceIgnoreCase(durationStr, "d", "")));
        } else {
            return Duration.of(Long.parseLong(durationStr), chronoUnitDefault);
        }
    }

    /**
     * 字符串转Duration，默认单位为秒
     * 天：d
     * 时、分、秒：h、m、s
     * 毫秒、微妙、纳秒：ms、us、ns
     *
     * @param durationStr 间隔字符串
     */
    public static Duration parseDuration(String durationStr) {
        return parseDuration(durationStr, ChronoUnit.SECONDS);
    }
}
